<template>
  <div>
    <div class="message-content" id="message-content">
      <div v-for="(message,index) in messageList" :class="userInfo.id===message.sender?'message-right':'message-left'">
        <p class="time">{{message.time}}</p>
        <div class="body">
          <img class="avatar" :src="showAvatar(message.sender)">
          <div class="text-message">
            <p v-show="message.type==='text'">{{message.content}}</p>
            <img v-show="message.type==='image'" @click="prePicFile(message.content)" width="150px" style="border-radius: 10px" :src="message.content">
            <a v-show="message.type==='video'" style="color: #0087e1" @click="toVideoRoom(message.content)">我发起了视频会议，点击进入</a>
          </div>
          <div v-show="userInfo.id===message.sender" class="check">
            <p :class="[checkId>=message.id?'read':'unread', 'right']">
              {{checkId>=message.id?'已读':'未读'}}
            </p>
          </div>

        </div>
      </div>
      <div style="height: 40px"></div>
      <el-image-viewer
        v-if="fileImage"
        :on-close="
        () => {
          (fileImage = false), (filePaths = '');
        }"
        :url-list="filePaths"
        style="margin-left: 400px"
      ></el-image-viewer>
    </div>
    <div class="im-chat-container">
      <div class="uploader-container">
        <el-upload
          class="avatar-uploader"
          :action="ipAddress+'/file/upload/'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <i class="el-icon-picture avatar-uploader-icon"></i>
        </el-upload>
<!--        <h4 style="margin-left: 10px" @click="video">发起视频会议</h4>-->
<!--        <h4 style="margin-left: 10px" @click="showEdit" v-show="doctorInfo.to===userInfo.id">填写\修改会诊意见</h4>-->
        <span class="suggest-edit" @click="video"><i class="el-icon-video-camera suggest-edit-icon"></i>发起视频会议</span>
        <span class="suggest-edit" @click="showEdit" v-show="doctorInfo.to===userInfo.id"><i class="el-icon-edit suggest-edit-icon"></i>填写\修改会诊意见</span>
      </div>
      <el-input
        type="textarea"
        :rows="6"
        placeholder="请输入内容"
        v-model="textarea"
        @keyup.enter="submit">
      </el-input>
      <p class="im-chat-send">
        <el-button type="info" @click="closeSession" size="mini">退出</el-button>
        <el-button type="warning" v-show="doctorInfo.to===userInfo.id" @click="endSession" size="mini">结束会诊</el-button>
        <el-button type="primary" @click="submit" size="mini">发送</el-button>
      </p>
    </div>
  </div>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import { mapGetters } from 'vuex'
import { sendMessage } from '../../../../utils/websocket'
import { getTimeNow } from '../../../../utils/myUtil'
export default {
  name: 'caseIm',
  data() {
    return {
      textarea: '',
      imageUrl: '',
      fileImage: false, // 组件的显示隐藏
      filePaths: [] // 因为预览组件是集
    }
  },
  components: {
    ElImageViewer
  },
  computed: {
    ...mapGetters(['messageList', 'userInfo', 'doctorInfo', 'chattingId', 'ipAddress', 'checkId'])
  },
  // 组件监听
  watch: {
    chattingId() {
      // 超时
      setTimeout(() => {
        const container = this.$el.querySelector('#message-content')
        container.scrollTop = container.scrollHeight
      }, 100)
    },
    // 获取所有信息
    messageList(newValue, oldValue) {
      this.$nextTick(() => {
        const container = this.$el.querySelector('#message-content')
        container.scrollTop = container.scrollHeight
      })
      // 更改后的信息
      const message = {
        messageID: newValue[newValue.length - 1].id,
        sessionID: this.chattingId,
        fromID: this.userInfo.id,
        toID: this.doctorInfo.from === this.userInfo.id ? this.doctorInfo.to : this.doctorInfo.from
      }// 发送消息
      sendMessage('check', message)
    }
  },
  methods: {
    // 进入视频房间
    toVideoRoom(roomId) {
      this.$confirm('是否进入视频会议？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        window.open(this.ipAddress + '/video?userId=' + this.userInfo.id + '&roomId=' + roomId, '_blank')
      })
    },
    randomString(len) { // 随机密码
      len = len || 32
      var $chars = '1234567890'
      var maxPos = $chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    // 发起视频会议
    video() {
      this.$confirm('是否发起视频会议？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const roomId = this.randomString(6)
        let receiver
        if (this.doctorInfo.from === this.userInfo.id) receiver = this.doctorInfo.to
        else receiver = this.doctorInfo.from
        const message = {
          consultationId: this.chattingId,
          sender: this.userInfo.id,
          receiver: receiver,
          type: 'video',
          content: roomId,
          time: getTimeNow()
        }
        sendMessage('message', message)
        window.open(this.ipAddress + '/video?userId=' + this.userInfo.id + '&roomId=' + roomId, '_blank')
      })
    },
    showEdit() {
      this.$emit('showEdit', this.doctorInfo)
    },
    submit() {
      if (this.textarea === '') return
      let receiver
      if (this.doctorInfo.from === this.userInfo.id) receiver = this.doctorInfo.to
      else receiver = this.doctorInfo.from
      const message = {
        consultationId: this.chattingId,
        sender: this.userInfo.id,
        receiver: receiver,
        type: 'text',
        content: this.textarea,
        time: getTimeNow()
      }
      sendMessage('message', message)
      this.textarea = ''
    },
    showAvatar(sender) {
      if (sender === this.userInfo.id) {
        return this.userInfo.avatar
      }
      if (this.doctorInfo.from === sender) return this.doctorInfo.fromAvatar
      else return this.doctorInfo.toAvatar
    },
    // 预览方法
    prePicFile(path) {
      this.filePaths = [path]
      this.fileImage = true
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      let receiver
      if (this.doctorInfo.from === this.userInfo.id) receiver = this.doctorInfo.to
      else receiver = this.doctorInfo.from
      const message = {
        consultationId: this.chattingId,
        sender: this.userInfo.id,
        receiver: receiver,
        type: 'image',
        content: res.data,
        time: getTimeNow()
      }
      sendMessage('message', message)
    },
    beforeAvatarUpload(file) { // 从系统文件上传图片
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/JPEG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    },
    closeSession() {
      this.$emit('closeSession', 1)
    },
    endSession() {
      this.$emit('endSession', this.doctorInfo)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
.check{
  font-size: 10px;
  margin-left: 5px;
  margin-right: 5px;
  position: relative;
  p{
    position: absolute;
    bottom: 0;
    width: 30px;
  }
  .right{
    right: -7px;
  }
}
  .unread{
    color: #0000ff;
  }
.message-content{
  height: 66%;
  border: groove;
  border-color: #7d7d7d;
  border-radius: 5px;
  overflow: scroll;
  .time{
    text-align: center;
    color: #7d7d7d;
  }
  .message-left{
    margin-top: 5px;
    .body{
      display: flex;
    }
    .avatar{
      margin-left: 5px;
      margin-right: 5px;
      border-radius: 20%;
      width: 50px;
      height: 50px;
    }
    .text-message{
      min-width: 2px;
      max-height: max-content;
      max-width: 70%;
      background-color: #8fc9fd;
      padding: 6px;
      border-radius: 5px;
      word-break: break-all; word-wrap:break-word;
    }
  }
  .message-right{
    margin-top: 5px;
    .body{
      flex-direction: row-reverse;-webkit-flex-direction: row-reverse;display: flex;
      .avatar{
        border-radius: 20%;
        width: 50px;
        height: 50px;
        margin-left: 5px;
        margin-right: 5px;
      }
      .text-message{
        word-wrap:break-word;
        float: right;
        max-width: 70%;
        width: max-content;
        background-color: #4dee05;
        padding: 6px;
        border-radius: 5px;
        margin-right: 0;

      }
    }
  }
}


.im-chat-container {
  .el-textarea__inner {
    border: gray solid;
    resize: none;
    padding: 0 10px;
  }
  .avatar-uploader .el-upload {
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
}


.im-chat-container {
  position: absolute;
  bottom: 0px;
  width: 100%;
  .uploader-container {
    border-top: 1px solid #d0d0d0;
    display: flex;
    .suggest-edit{
      color: #8c939d;
      font-size: 12px;
      cursor: pointer;
      &-icon{
        font-size: 28px;
        width: 40px;
        height: 40px;
        line-height: 40px;
        text-align: center;
      }
    }
  }
  .im-chat-send {
    text-align: right;
    padding: 5px 10px;
  }
}
</style>
